package com.zx.sdk.league.member;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.zx.sdk.ZxSDK;
import com.zx.sdk.listener.BaseZxRewardListener;
import com.zx.sdk.listener.BaseZxSplashListener;
import com.zx.sdk.model.AdInfo;
import com.zx.sdk.model.ZxError;
import com.zx.sdk.util.RunnableHelper;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import cn.jiguang.jgssp.ADJgSdk;
import cn.jiguang.jgssp.ad.ADJgInterstitialAd;
import cn.jiguang.jgssp.ad.ADJgRewardVodAd;
import cn.jiguang.jgssp.ad.ADJgSplashAd;
import cn.jiguang.jgssp.ad.data.ADJgAdInfo;
import cn.jiguang.jgssp.ad.data.ADJgInterstitialAdInfo;
import cn.jiguang.jgssp.ad.data.ADJgRewardVodAdInfo;
import cn.jiguang.jgssp.ad.entity.ADJgAdSize;
import cn.jiguang.jgssp.ad.entity.ADJgExtraParams;
import cn.jiguang.jgssp.ad.entity.ADJgRewardExtra;
import cn.jiguang.jgssp.ad.error.ADJgError;
import cn.jiguang.jgssp.ad.listener.ADJgInterstitialAdListener;
import cn.jiguang.jgssp.ad.listener.ADJgRewardVodAdListener;
import cn.jiguang.jgssp.ad.listener.ADJgSplashAdListener;
import cn.jiguang.jgssp.config.ADJgInitConfig;
import cn.jiguang.jgssp.config.CustomDeviceInfoController;
import cn.jiguang.jgssp.util.ADJgAdUtil;

public class JiGuang extends BaseLeagueMember<Object, Object, Object, ADJgInterstitialAdInfo, Object> {
    @Override
    public String getName() {
        return "jg";
    }

    @Override
    protected void onInit(Context context, String appId, boolean initialized) {
        RunnableHelper.runOnUIThread(() -> {// 必须在主线程中进行
            ADJgSdk.getInstance().init(context, new ADJgInitConfig.Builder()
                    // 设置APPID，必须的
                    .appId(appId)
                    // 是否开启Debug，开启会有详细的日志信息打印，如果用上ADJgToastUtil工具还会弹出toast提示。
                    // 注意上线后请置为false
                    .debug(ZxSDK.isDebug())
                    // 是否同意隐私政策
                    .agreePrivacyStrategy(true)
                    // 是否同意使用oaid
                    .isCanUseOaid(true)
                    // 是否可读取wifi状态
                    .isCanUseWifiState(true)
                    // 是否可获取定位数据
                    .isCanUseLocation(true)
                    // 是否可获取设备信息
                    .isCanUsePhoneState(true)
                    // 是否过滤第三方平台的问题广告（例如: 已知某个广告平台在某些机型的Banner广告可能存在问题，如果开启过滤，则在该机型将不再去获取该平台的Banner广告）
                    .filterThirdQuestion(true)
                    // 是否可读取设备安装列表
                    .isCanReadInstallList(true)
                    // 是否可读取设备外部读写权限
                    .isCanUseReadWriteExternal(true)
                    .setCustomDeviceInfoController(new CustomDeviceInfoController() {
                        /**
                         * 当isCanUsePhoneState=false时，可传入imei信息，天目使用您传入的imei信息
                         * @return imei信息
                         */
                        @Override
                        public String getImei() {
                            return super.getImei();
                        }

                        /**
                         * 当isCanUsePhoneState=false时，可传入AndroidId信息，天目使用您传入的AndroidId信息
                         * @return androidid信息
                         */
                        @Override
                        public String getAndroidId() {
                            return super.getAndroidId();
                        }

                        /**
                         * 当isCanUseLocation=false时，可传入地理位置信息，天目使用您传入的地理位置信息
                         * @return 极光地理位置参数JUnionLocationProvider
                         */
                        @Override
                        public Location getLocation() {
                            return super.getLocation();
                        }

                        /**
                         * 当isCanUseWifiState=false时，可传入Mac地址信息，天目使用您传入的Mac地址信息
                         * @return Mac地址
                         */
                        @Override
                        public String getMacAddress() {
                            return super.getMacAddress();
                        }

                        /**
                         * 开发者可以传入oaid ，若不传或为空值，则不使用oaid信息
                         * @return oaid
                         */
                        @Override
                        public String getOaid() {
                            return ZxSDK.oaid;
                        }

                        /**
                         * 开发者可以传入vaid ，若不传或为空值，则不使用oaid信息
                         * @return vaid
                         */
                        @Override
                        public String getVaid() {
                            return ZxSDK.vaid;
                        }
                    })
                    .build());
        });
    }

    @Override
    protected void onLoadSplash(AdInfo adInfo, ViewGroup container, String mode, String type, BaseZxSplashListener listener) {
        RunnableHelper.runOnUIThread(() -> {
            if (AdInfo.AD_TYPE_EXPRESS_INTERSTITIAL_AD == adInfo.getAdType()) {
                onLoadInterstitial((Activity) container.getContext(), adInfo, mode, type, new BaseZxRewardListener() {
                    @Override
                    public void onADClick() {
                        listener.onADClicked();
                    }

                    @Override
                    public void onADClose() {
                        listener.onADDismissed();
                    }

                    @Override
                    public void onADExpose() {
                        listener.onADExposure();
                    }

                    @Override
                    public void onADLoad() {
                        listener.onADLoaded(0L);
                    }

                    @Override
                    public void onReward(@NonNull Map<String, Object> map) {

                    }

                    @Override
                    public void onVideoCached() {

                    }

                    @Override
                    public void onVideoComplete() {

                    }

                    @Override
                    public void onPreLoadADError(ZxError error) {
                        listener.onPreLoadNoAD(error);
                    }

                    @Override
                    public void onRewardStepVerify(int taskType, int currentTaskStatus) {

                    }

                    @Override
                    public void onAdSkip(float v) {

                    }

                    @Override
                    public void onVideoPlayError(ZxError error) {
                    }

                    @Override
                    public void onNoAD(ZxError error) {
                        listener.onNoAD(error);
                    }

                    @Override
                    public void onPreloading() {
                        listener.onPreloading();
                    }

                    @Override
                    public void onLoaded() {
                        listener.onLoaded();
                    }
                });
                return;
            }
            // 创建开屏广告实例，第一个参数可以是Activity或Fragment，第二个参数是广告容器
            ADJgSplashAd adJgSplashAd = new ADJgSplashAd((Activity) container.getContext(), container);
            ADJgExtraParams extraParams = new ADJgExtraParams.Builder().adSize(new ADJgAdSize(container.getWidth(), container.getHeight())).build();
            // 如果开屏容器不是全屏可以设置额外参数
            adJgSplashAd.setLocalExtraParams(extraParams);
            // 设置是否是沉浸式，如果为true，跳过按钮距离顶部的高度会加上状态栏高度
            adJgSplashAd.setImmersive(false);
            // 设置开屏广告监听
            adJgSplashAd.setListener(new ADJgSplashAdListener() {
                @Override
                public void onADTick(long countdownSeconds) {
                    listener.onADTick(JiGuang.this, countdownSeconds, adInfo);
                }

                @Override
                public void onReward(ADJgAdInfo adJgAdInfo) {

                }

                @Override
                public void onAdSkip(ADJgAdInfo adJgAdInfo) {
                }

                @Override
                public void onAdReceive(ADJgAdInfo adJgAdInfo) {
                    listener.onADLoaded(JiGuang.this, 0, adInfo);
                    if (ZxSDK.FETCH_ONLY.equals(mode)) {
                        saveSplash(adInfo.getMapPid(), adJgSplashAd, container);
                    }
                }

                @Override
                public void onAdExpose(ADJgAdInfo adJgAdInfo) {
                    listener.onADExposure(JiGuang.this, adInfo);
                }

                @Override
                public void onAdClick(ADJgAdInfo adJgAdInfo) {
                    listener.onADClicked(JiGuang.this, adInfo);
                }

                @Override
                public void onAdClose(ADJgAdInfo adJgAdInfo) {
                    listener.onADDismissed(JiGuang.this, adInfo);
                }

                @Override
                public void onAdFailed(ADJgError adJgError) {
                    switch (mode) {
                        case ZxSDK.FETCH_ONLY:
                            listener.onPreLoadNoAD(JiGuang.this, new ZxError(String.valueOf(adJgError.getCode()), adJgError.getError()), adInfo);
                            break;
                        case ZxSDK.FETCH_AND_SHOW:
                            listener.onNoAD(JiGuang.this, new ZxError(String.valueOf(adJgError.getCode()), adJgError.getError()), adInfo);
                            break;
                    }
                }
            });
            // 加载开屏广告
            switch (mode) {
                case ZxSDK.FETCH_ONLY:
                    adJgSplashAd.loadOnly(adInfo.getMapPid());
                    break;
                case ZxSDK.FETCH_AND_SHOW:
                    adJgSplashAd.loadAd(adInfo.getMapPid());
                    break;
            }
        });
    }

    @Override
    public boolean onShowSplash(AdInfo adInfo, ViewGroup container, @Nullable Object splash, BaseZxSplashListener listener) {
        if (splash instanceof ADJgInterstitialAdInfo && showInterstitial((Activity) container.getContext(), adInfo, null)) {
            return true;
        } else if (splash instanceof ADJgSplashAd) {
            ((ADJgSplashAd) splash).showSplash();
            return true;
        }
        return false;
    }

    @Override
    public void onLoadReward(Activity context, AdInfo adInfo, String mode, String type, BaseZxRewardListener listener) {
        RunnableHelper.runOnUIThread(() -> {
            if (AdInfo.AD_TYPE_EXPRESS_INTERSTITIAL_AD == adInfo.getAdType()) {
                onLoadInterstitial(context, adInfo, mode, type, listener);
                return;
            }
            // 创建激励视频广告实例
            ADJgRewardVodAd rewardVodAd = new ADJgRewardVodAd(context);
            ADJgRewardExtra adJgRewardExtra = new ADJgRewardExtra(ZxSDK.getUid());
            // 设置激励视频服务端验证的自定义信息
            // adJgRewardExtra.setCustomData("设置激励视频服务端验证的自定义信息");
            // 设置激励视频服务端激励名称(mintegral渠道不支持)
            // adJgRewardExtra.setRewardName("激励名称");
            // 设置激励视频服务端激励数量(mintegral渠道不支持)
            // adJgRewardExtra.setRewardAmount(1);
            // 创建额外参数实例
            ADJgExtraParams extraParams = new ADJgExtraParams.Builder()
                    // 设置激励视频额外参数（可不设置）
                    .rewardExtra(adJgRewardExtra)
                    // 设置视频类广告是否静音（部分渠道支持）
                    .setVideoWithMute(false)
                    .build();
            rewardVodAd.setLocalExtraParams(extraParams);
            // 设置激励视频广告监听
            rewardVodAd.setListener(new ADJgRewardVodAdListener() {

                @Override
                public void onAdReceive(ADJgRewardVodAdInfo rewardVodAdInfo) {
                    switch (mode) {
                        case ZxSDK.FETCH_ONLY:
                            saveReward(adInfo.getMapPid(), rewardVodAdInfo);
                            break;
                        case ZxSDK.FETCH_AND_SHOW:
                            ADJgAdUtil.showRewardVodAdConvenient(context, rewardVodAdInfo);
                            break;
                    }
                    listener.onADLoad(JiGuang.this, adInfo);
                }

                @Override
                public void onVideoCache(ADJgRewardVodAdInfo adJgRewardVodAdInfo) {
                    listener.onVideoCached(JiGuang.this, adInfo);
                }

                @Override
                public void onVideoComplete(ADJgRewardVodAdInfo adJgRewardVodAdInfo) {
                    listener.onVideoComplete(JiGuang.this, adInfo);
                }

                @Override
                public void onVideoError(ADJgRewardVodAdInfo adJgRewardVodAdInfo, ADJgError adJgError) {
                    listener.onVideoPlayError(JiGuang.this, new ZxError(adJgError.getCode() + "", adJgError.getError()), adInfo);
                }

                @Override
                public void onReward(ADJgRewardVodAdInfo adJgRewardVodAdInfo) {
                    listener.onReward(JiGuang.this, Collections.emptyMap(), adInfo);
                }

                @Override
                public void onAdExpose(ADJgRewardVodAdInfo adJgRewardVodAdInfo) {
                    listener.onADExpose(JiGuang.this, adInfo);
                }

                @Override
                public void onAdClick(ADJgRewardVodAdInfo adJgRewardVodAdInfo) {
                    listener.onADClick(JiGuang.this, adInfo);
                }

                @Override
                public void onAdClose(ADJgRewardVodAdInfo adJgRewardVodAdInfo) {
                    listener.onADClose(JiGuang.this, adInfo);
                }

                @Override
                public void onAdFailed(ADJgError adJgError) {
                    int code = -1;
                    String errorMsg = "加载失败";
                    if (adJgError != null) {
                        code = adJgError.getCode();
                        errorMsg = adJgError.getError();
                    }
                    switch (mode) {
                        case ZxSDK.FETCH_ONLY:
                            listener.onPreLoadADError(JiGuang.this, new ZxError(String.valueOf(code), errorMsg), adInfo);
                            break;
                        case ZxSDK.FETCH_AND_SHOW:
                            listener.onNoAD(JiGuang.this, new ZxError(String.valueOf(code), errorMsg), adInfo);
                            break;
                    }
                }
            });
            // 激励广告场景id（场景id非必选字段，如果需要可到开发者后台创建）
            // rewardVodAd.setSceneId(ADJgDemoConstant.REWARD_VOD_AD_SCENE_ID);
            // 加载激励视频广告，参数为广告位ID
            rewardVodAd.loadAd(adInfo.getMapPid());
        });
    }

    @Override
    public boolean onShowReward(Activity context, AdInfo adInfo, @Nullable Object reward, BaseZxRewardListener listener) {
        if (reward instanceof ADJgInterstitialAdInfo && showInterstitial(context, adInfo, listener)) {
            return true;
        } else if (reward instanceof ADJgRewardVodAdInfo) {
            ADJgAdUtil.showRewardVodAdConvenient(context, (ADJgRewardVodAdInfo) reward);
            return true;
        }
        return false;
    }

    @Override
    public void onLoadInterstitial(Activity context, AdInfo adInfo, String mode, String type, BaseZxRewardListener listener) {
        RunnableHelper.runOnUIThread(() -> {
            ADJgInterstitialAd interstitialAd = new ADJgInterstitialAd(context);
            interstitialAd.setListener(new ADJgInterstitialAdListener() {

                @Override
                public void onAdReceive(ADJgInterstitialAdInfo adv) {
                    switch (mode) {
                        case ZxSDK.FETCH_ONLY:
                            if (ZxSDK.SPLASH.equals(adInfo.getDisplay())) {
                                saveSplash(adInfo.getMapPid(), adv, null);
                            } else if (ZxSDK.REWARD.equals(adInfo.getDisplay())) {
                                saveReward(adInfo.getMapPid(), adv);
                            } else if (ZxSDK.INTERSTITIAL.equals(adInfo.getDisplay())) {
                                saveInterstitial(adInfo.getMapPid(), adv);
                            }
                            break;
                        case ZxSDK.FETCH_AND_SHOW:
                            adv.showInterstitial(context);
                            break;
                    }
                }

                @Override
                public void onAdReady(ADJgInterstitialAdInfo adInfo) {
                }

                @Override
                public void onAdExpose(ADJgInterstitialAdInfo adv) {
                    listener.onADExpose(JiGuang.this, adInfo);
                }

                @Override
                public void onAdClick(ADJgInterstitialAdInfo adv) {
                    listener.onADClick(JiGuang.this, adInfo);
                }

                @Override
                public void onAdClose(ADJgInterstitialAdInfo adv) {
                    if (ZxSDK.REWARD.equals(adInfo.getDisplay())) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("Id", adInfo.getMapPid());
                        listener.onReward(JiGuang.this, map, adInfo);
                    }
                    listener.onADClose(JiGuang.this, adInfo);
                }

                @Override
                public void onAdFailed(ADJgError error) {
                    switch (mode) {
                        case ZxSDK.FETCH_ONLY:
                            listener.onPreLoadADError(JiGuang.this, new ZxError(String.valueOf(error.getCode()), error.getError()), adInfo);
                            break;
                        case ZxSDK.FETCH_AND_SHOW:
                            listener.onNoAD(JiGuang.this, new ZxError(String.valueOf(error.getCode()), error.getError()), adInfo);
                            break;
                    }
                }
            });
            interstitialAd.loadAd(adInfo.getMapPid());
        });
    }

    @Override
    public boolean onShowInterstitial(Activity context, AdInfo adInfo, @Nullable ADJgInterstitialAdInfo interstitial, BaseZxRewardListener listener) {
        try {
            interstitial.showInterstitial(context);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean isPreResReady(String type, String pid) {
        Object rewardVodAdInfo = getFilledRewardByPid(pid);
        if (rewardVodAdInfo instanceof ADJgRewardVodAdInfo) {
            try {
                //rewardVodAdInfo.hasExpired() 可能报空指针
                return !((ADJgRewardVodAdInfo) rewardVodAdInfo).hasShown() && ((ADJgRewardVodAdInfo) rewardVodAdInfo).isReady() && !((ADJgRewardVodAdInfo) rewardVodAdInfo).isReleased() && !((ADJgRewardVodAdInfo) rewardVodAdInfo).hasExpired();
            } catch (Exception e) {
                return false;
            }
        }
        return super.isPreResReady(type, pid);
    }
}
